package com.paad.todolist;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ToDoList extends Activity {

    static final private int ADD_NEW_TODO = Menu.FIRST;
    static final private int REMOVE_TODO = Menu.FIRST + 1;

    private boolean addingNew = false;
    private ArrayList<String> todoItems;
    private ListView myListView;
    private EditText myEditText;
    private ArrayAdapter<String> aa;
    private static final int PICK_CONTACT_SUBACTIVITY = 2;

    /**
     * Called when the activity is first created.
     */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Inflate your view
        setContentView(R.layout.main);

        // Get references to UI widgets
        myListView = (ListView) findViewById(R.id.myListView);
        myEditText = (EditText) findViewById(R.id.myEditText);

        todoItems = new ArrayList<String>();

        int resID = R.layout.todolist_item;
        aa = new ArrayAdapter<String>(this, resID, todoItems);
        myListView.setAdapter(aa);

        myEditText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("GUIKEY", "onKey: " + event.getAction() + "," + keyCode);
                if (event.getAction() == KeyEvent.ACTION_DOWN)
//          if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                    if (keyCode == KeyEvent.KEYCODE_ENTER) {
                        todoItems.add(0, myEditText.getText().toString());
                        myEditText.setText("");
                        aa.notifyDataSetChanged();
                        cancelAdd();
                        return true;
                    }
                return false;
            }
        });

        registerForContextMenu(myListView);

        Button diagbtn = (Button) findViewById(R.id.buttondiag);
        diagbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐式创建一个意图
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:155-1048-2603"));
                startActivity(intent);
            }
        });

        Button pickpeoplebtn = (Button) findViewById(R.id.buttonpickpeople);
        pickpeoplebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Uri uri = Uri.parse("content://contacts/people");
                Intent intent = new Intent(Intent.ACTION_PICK, uri);
                startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);

            }
        });

        Button btncallme = (Button) findViewById(R.id.buttoncallme);
        btncallme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Uri uri = Uri.parse("tel:" + "155-1048-2603");
                Intent intent = new Intent(Intent.ACTION_CALL, uri);
                startActivity(intent);


            }
        });


//        在子活动中找到启动意图
        Intent subIntent = getIntent();
        String action = subIntent.getAction();
        Uri data = subIntent.getData();
        Log.i("GUIKEY", "onCreate: getaction:" + action);
        Log.i("GUIKEY", "onCreate: getdata  :" + data);

    }

    @Override
    public void onActivityResult(int reqCode, int resCode, Intent data) {
        super.onActivityResult(reqCode, reqCode, data);
        switch (reqCode) {
            case PICK_CONTACT_SUBACTIVITY: {
                if (resCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor c = this.getContentResolver().query(contactData, null, null, null
                            , null);
                    c.moveToFirst();
                    String result = "";
                    //联系人姓名
                    String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                    // 条件为联系人ID
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    TextView tv = (TextView) findViewById(R.id.selected_contact_textview2);
                    //查看该联系人有多少个电话号码。如果没有这返回值为0
                    int phoneCount = c.getInt(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    result = name;
                    if(phoneCount>0){
                        //获得联系人的电话号码
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = " + contactId, null, null);
                        if(phones.moveToFirst()){
                            do{
                                //遍历所有的电话号码
                                String phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                System.out.println(phoneNumber);
                                result += ":";
                                result += phoneNumber;
                            }while(phones.moveToNext());
                        }
                    }
                    tv.setText(result);
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // Create and add new menu items.
        MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE,
                R.string.add_new);
        MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE,
                R.string.remove);

        // Assign icons
        itemAdd.setIcon(R.drawable.add_new_item);
        itemRem.setIcon(R.drawable.remove_item);

        // Allocate shortcuts to each of them.
        itemAdd.setShortcut('0', 'a');
        itemRem.setShortcut('1', 'r');

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        int idx = myListView.getSelectedItemPosition();
        Log.i("GUI", "onPrepareOptionsMenu: addingNew:" + addingNew);

        String removeTitle = getString(addingNew ?
                R.string.cancel : R.string.remove);

        MenuItem removeItem = menu.findItem(REMOVE_TODO);
        removeItem.setTitle(removeTitle);
        removeItem.setVisible(addingNew || idx > -1);

        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu,
                                    View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        menu.setHeaderTitle("Selected To Do Item");
        menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        int index = myListView.getSelectedItemPosition();

        switch (item.getItemId()) {
            case (REMOVE_TODO): {
                if (addingNew) {
                    cancelAdd();
                } else {
                    removeItem(index);
                }
                return true;
            }
            case (ADD_NEW_TODO): {
                addNewItem();
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        super.onContextItemSelected(item);
        switch (item.getItemId()) {
            case (REMOVE_TODO): {
                AdapterView.AdapterContextMenuInfo menuInfo;
                menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                int index = menuInfo.position;

                removeItem(index);
                return true;
            }
        }
        return false;
    }

    private void cancelAdd() {
        addingNew = false;
        myEditText.setVisibility(View.GONE);
    }

    private void addNewItem() {
        addingNew = true;
        myEditText.setVisibility(View.VISIBLE);
        myEditText.requestFocus();
    }

    private void removeItem(int _index) {
        todoItems.remove(_index);
        aa.notifyDataSetChanged();
    }
}